<template>
    <div class="outer-order-page">
      <el-button type="primary" @click="saveAll">保存</el-button>
      <el-button type="primary" @click="goBack">工序列表</el-button>
      <!-- 基本信息部分 -->
      <br/><br/>
      <el-card title="基本信息">
        <el-form 
          :model="form" 
          label-width="120px" 
          ref="formRef" 
          :rules="rules"
        >
          <el-row>
            <el-col :span="10">
              <el-form-item label="工艺名称" prop="craftsmanshipName">
                <el-input v-model="form.craftsmanshipName" required></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="工艺编码" prop="craftsmanshipCode">
                <el-input placeholder="保存后自动生成" disabled v-model="form.craftsmanshipCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="负责人" prop="leader">
                <el-input
                    v-model="form.leader"
                    :readonly="form.ourRepresentativesInfoFilled"
                    required
                >
                  <template #suffix>
                    <el-button size="mini" @click="openOurRepresentativesDialog">
                      <i class="el-icon-search"></i>
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属部门">
                <el-input v-model="form.affiliation" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="状态">
                <el-switch v-model="form.status"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="备注">
                <el-input type="textarea" v-model="form.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </el-card>

      <!-- 工序列表区域 -->
      <el-card title="工序列表" style="margin-top: 20px; border-top: 3px solid #409eff;">
        <div class="table-container">
          <el-table 
            :data="planList" 
            stripe 
            ref="tableRef" 
            height="300"
            @selection-change="handleSelectionChange"
          >
            <el-table-column>
              <template #header>
                <el-checkbox 
                  v-model="allChecked" 
                  :indeterminate="indeterminate" 
                  @change="handleCheckAllChange"
                ></el-checkbox>
              </template>
              <template #default="scope">
                <el-checkbox 
                  :model-value="checkedIds.has(scope.row.procedureId)" 
                  @update:model-value="handleRowCheck(scope.row.procedureId, $event)"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="80"></el-table-column>
            <el-table-column prop="processCode" label="工序编码" width="150"></el-table-column>
            <el-table-column prop="processName" label="工序名称"></el-table-column>
            <el-table-column prop="typeName" label="工序类型"></el-table-column>
            <el-table-column prop="leader" label="负责人"></el-table-column>
            <el-table-column prop="affiliation" label="所属部门" width="100"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.status === true ? 'success' : 'danger'">
                  {{ scope.row.status === true ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="180"></el-table-column>
          </el-table>
        </div>
        
        <!-- 分页部分 -->
        <div class="demo-pagination-block" style="margin-top: 15px;">
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[10, 20, 30, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 负责人选择对话框 -->
      <el-dialog
            v-model="ourRepresentativesDialogVisible"
            width="500px"
            title="我方代表选择"
            append-to-body
        >
            <el-table
                :data="ourRepresentativesList"
                highlight-current-row
                border
                size="small"
                @current-change="handleOurRepresentativesChange"
            >
                <el-table-column type="index" label="序号" />
                <el-table-column property="userName" label="代表姓名" />
                <el-table-column property="depmentName" label="部门" />
                <el-table-column property="roleName" label="职位" />
            </el-table>
            <template #footer>
                <el-button @click="ourRepresentativesDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="pickOurRepresentatives">确定</el-button>
            </template>
        </el-dialog>
    </div>
  </template>

  <script setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { ElMessage, ElLoading } from 'element-plus';
  import axios from 'axios';
  import { useRouter } from 'vue-router';

  const router = useRouter();
  // 表单验证规则
  const rules = reactive({
    craftsmanshipName: [{ required: true, message: '请输入工艺名称', trigger: 'blur' }],
    leader: [{ required: true, message: '请选择负责人', trigger: 'blur' }]
  });

  // 基本信息表单数据
  const form = ref({
    craftsmanshipCode: "",
    craftsmanshipName: "",
    leader: "",
    affiliation: "",
    status: true,
    remark: "",
    ourRepresentativesInfoFilled: false
  });

  // 分页对象
  const page = ref({
    PageIndex: 1,
    PageSize: 20,
  });

  // 分页总数
  const total = ref({
    totalCount: 0,
    totalPage: 0,
  });

  // 表单ref
  const formRef = ref(null);

  // 选中行管理
  const checkedIds = ref(new Set()); // 使用Set存储选中的ID
  const allChecked = ref(false); // 全选状态
  const indeterminate = computed(() => { // 半选状态
    return checkedIds.value.size > 0 && checkedIds.value.size < planList.value.length;
  });

  // 工序列表数据
  const planList = ref([]);

  // 我方代表列表
  const ourRepresentativesList = ref([]);
  const currentOurRepresentative = ref(null);
  const ourRepresentativesDialogVisible = ref(false);

  // 生命周期钩子
  onMounted(() => {
    fetchBaseData();
    fetchProcedureList();
  });

  // 获取基础数据
  const fetchBaseData = async () => {
    try {
      const { data } = await axios.get('http://8.154.44.176:8000/r-read/api/Depment/GetDepUserRole');
      ourRepresentativesList.value = data.data || [];
      console.log('我方代表数据加载成功', ourRepresentativesList.value);
    } catch (error) {
      ElMessage.error('加载我方代表失败');
      console.error('加载我方代表失败:', error);
    }
  };

  // 获取工序列表
  const fetchProcedureList = async () => {
    try {
      const { data } = await axios.get('http://8.154.44.176:8000/f-read/api/GetProcess/GetProcedure', {
        params: {
          PageIndex: page.value.PageIndex,
          PageSize: page.value.PageSize,
        }
      });
      
      if (data.code === 200) {
        planList.value = data.data.list || [];
        total.value.totalCount = data.data.totalCount || 0;
        resetSelection();
        console.log('工序列表加载成功', planList.value);
      } else {
        ElMessage.error(`获取工序数据失败：${data.message}`);
        console.error('获取工序数据失败:', data.message);
      }
    } catch (error) {
      ElMessage.error('获取工序数据失败，请检查网络或联系管理员');
      console.error('获取工序列表失败:', error);
    }
  };

  // 重置选中状态
  const resetSelection = () => {
    checkedIds.value.clear();
    allChecked.value = false;
  };

  // 处理行选中状态变化
  const handleRowCheck = (id, checked) => {
    if (checked) {
      checkedIds.value.add(id);
    } else {
      checkedIds.value.delete(id);
    }
    updateAllCheckedStatus();
    console.log('当前选中的工序ID:', Array.from(checkedIds.value));
  };

  // 处理全选/反选
  const handleCheckAllChange = (value) => {
    checkedIds.value.clear();
    if (value) {
      planList.value.forEach(item => checkedIds.value.add(item.procedureId));
    }
    updateAllCheckedStatus();
    console.log('全选操作后选中的工序ID:', Array.from(checkedIds.value));
  };

  // 更新全选状态
  const updateAllCheckedStatus = () => {
    allChecked.value = checkedIds.value.size > 0 && checkedIds.value.size === planList.value.length;
  };

  // 分页相关
  const handleSizeChange = (val) => {
    page.value.PageSize = val;
    fetchProcedureList();
  };

  const handleCurrentChange = (val) => {
    page.value.PageIndex = val;
    fetchProcedureList();
  };

  // 打开工序负责人对话框
  const openOurRepresentativesDialog = () => {
    if (ourRepresentativesList.value.length === 0) {
      ElMessage.warning('工序负责人数据加载中，请稍后重试');
      return;
    }
    ourRepresentativesDialogVisible.value = true;
  };

  // 处理工序负责人行选中
  const handleOurRepresentativesChange = (val) => {
    currentOurRepresentative.value = val;
  };

  // 选择工序负责人并填充数据
  const pickOurRepresentatives = () => {
    if (currentOurRepresentative.value) {
      form.value.leader = currentOurRepresentative.value.userName;
      form.value.affiliation = currentOurRepresentative.value.depmentName;
      form.value.ourRepresentativesInfoFilled = true;
      ourRepresentativesDialogVisible.value = false;
    } else {
      ElMessage.warning('请选择一个我方代表');
    }
  };

  // 保存工艺和工序关系
  const saveAll = async () => {
    if (!formRef.value) return;
    
    try {
      await formRef.value.validate();
      
      if (checkedIds.value.size === 0) {
        ElMessage.warning('请至少选择一个工序');
        return;
      }
      
      // 显示加载状态
      const loading = ElLoading.service({
        lock: true,
        text: '正在保存数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      try {
        // 保存主表单
        const { data } = await axios.post(
          'http://8.154.44.176:8000/f-write/api/Process/AddCraftsmanship',
          form.value
        );

        if (data.code === 200) {
          ElMessage.success('工艺保存成功');
          
          // 获取主表主键
          const craftsmanshipId = data.data?.productionPlanningId;
          if (!craftsmanshipId) {
            ElMessage.error('未能获取工艺表主键（craftsmanshipId）');
            console.error('主表响应数据:', data);
            return;
          }
          
          // 逐条保存工艺工序关系
          await saveCraftProcedureRelationSequentially(craftsmanshipId);
          
          fetchProcedureList();
          resetSelection();
        } else {
          ElMessage.error(`保存失败：${data.message}`);
        }
      } finally {
        // 关闭加载状态
        loading.close();
      }
    } catch (error) {
      ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
      console.error('保存失败:', error);
    }
  };

  // 逐条保存工艺工序关系
  const saveCraftProcedureRelationSequentially = async (craftsmanshipId) => {
    const procedureIds = Array.from(checkedIds.value);
    let successCount = 0;
    let errorCount = 0;
    const errors = [];

    for (const procedureId of procedureIds) {
      try {
        // 构建单条关系数据
        const relationData = {
          craftsmanshipId,
          procedureId
        };
        
        console.log('正在保存关系:', relationData);
        
        const { data } = await axios.post(
          'http://8.154.44.176:8000/f-write/api/Process/AddCraftProcedure',
          relationData // 注意：这里直接传递单条数据，而非数组
        );
        
        if (data.code === 200) {
          successCount++;
          console.log(`工序ID ${procedureId} 关系保存成功`);
        } else {
          errorCount++;
          errors.push(`工序ID ${procedureId}: ${data.message}`);
          console.error(`保存关系失败：${data.message}`);
        }
      } catch (error) {
        errorCount++;
        errors.push(`工序ID ${procedureId}: 网络错误`);
        console.error(`保存工序ID ${procedureId} 关系失败`, error);
      }
    }

    // 显示保存结果
    if (errorCount === 0) {
      ElMessage.success(`成功保存 ${successCount} 条工艺工序关系`);
    } else {
      ElMessage.warning(`成功保存 ${successCount} 条，失败 ${errorCount} 条`);
      console.error('保存失败的工序:', errors);
    }
  };

  const goBack = () => {
    router.push('/GetCraftsmanshipView');
  }
</script>
